package cn.edu.ecnu.gis.client;

import java.util.Iterator;
import java.util.Map.Entry;

import com.google.gwt.gears.core.client.GearsException;
import com.google.gwt.gears.database.client.Database;
import com.google.gwt.gears.database.client.ResultSet;

public class GearsStorage extends Storage
{
	public GearsStorage(){
		super();
	}

	public static native boolean isGearsInstalled() /*-{
		try { 
	   		return $wnd.google.gears.factory != null;
	   	} catch (e) {
			return false;
		}

	}-*/;

	public void load() throws StorageException {
		getValues().clear();
		
		//check for gears installation
		if( ! isGearsInstalled() )
			throw new StorageException("load failed, Gears is not installed");

		try {
			//select from the database
			Database db = new Database("Storage");
			ResultSet rs = db.execute("select * from Storage");

			for (int i = 0; rs.isValidRow(); ++i, rs.next()){
				getValues().put(rs.getFieldAsString(0), rs.getFieldAsString(1));
			}
			rs.close();

		} catch (GearsException e) {
			throw new StorageException( e.getMessage(), e );
		}
	}

	public void save() throws StorageException {
		//check for gears installation
		if( ! isGearsInstalled() )
			throw new StorageException("save failed, Gears is not installed");
		
		try {					
			//create the Storage table if it doesn't exist
			Database db = new Database("Storage");
			db.execute("create table if not exists Storage (key varchar(255), value text)");
			
			//add the list to the table			
			for( Iterator iter = getValues().entrySet().iterator(); iter.hasNext(); )
			{
				Entry entry = (Entry) iter.next();
			    db.execute("insert into Storage values (?, ?)", new String[] {
			    		(String)entry.getKey(), 
			    		(String)entry.getValue()
			    	});
			}
		} catch (GearsException e) {
			throw new StorageException( "save failed", e );
		}
	}

}
